<?php

namespace addons\JhxEdu\services\order;

use addons\JhxEdu\common\enums\AccessTokenGroupEnum;
use addons\JhxEdu\common\models\product\Product;
use common\helpers\BcHelper;
use common\enums\PayTypeEnum;
use common\enums\StatusEnum;
use Yii;
use yii\data\Pagination;
use yii\db\ActiveQuery;
use yii\web\UnprocessableEntityHttpException;
use common\helpers\ArrayHelper;
use common\helpers\AddonHelper;
use common\helpers\StringHelper;
use common\helpers\EchantsHelper;
use common\models\member\Member;
use common\models\member\Account;
use addons\JhxEdu\common\models\common\MemberVip;
use addons\JhxEdu\common\models\order\Order;
use addons\JhxEdu\common\models\order\DistributeLog;
use addons\JhxEdu\common\models\order\OrderProduct;
use addons\JhxEdu\common\models\forms\OrderQueryForm;
/**
 * Class OrderService
 * @package addons\JhxEdu\services\order
 * @author jianyan74 <751393839@qq.com>
 */
class OrderService extends \common\components\Service
{
    protected $_setting;

    /**
     * 创建订单
     *
     * @param PreviewForm $previewForm
     * @return Order
     * @throws UnprocessableEntityHttpException
     */
    public function create(Order $previewForm)
    {
        $config = AddonHelper::getConfig();
        // 生成订单
        $order = $previewForm;
        $order = $order->loadDefaultValues();
        $order->attributes = ArrayHelper::toArray($previewForm);
        $order->status = 1; //创建待支付
        $order->order_sn = date('YmdHis') . StringHelper::random(10, true);
        $order->buyer_ip = Yii::$app->request->userIP;
        //获取商品

        $order->orderProducts = Product::find()->where(['id'=>$order->products_id,'status'=>1])->all();
        if(!$order->orderProducts || empty($order->orderProducts)){
            throw new UnprocessableEntityHttpException('课程不存在');
        }
        //检查限购,正常情况下课程属于虚拟商品，用户仅需购买一次。
        $buyed = OrderProduct::find()->where(['product_id'=>$order->products_id,'member_id'=>$order->member_id])->all();
        foreach ($order->orderProducts as $key => $value) {
            foreach ($buyed as $key => $b) {
                if($value->id == $b->product_id){
                    throw new UnprocessableEntityHttpException('您已购买过该课程，无需重复购买');
                }
            }
        }
        //计算价格
        $order->order_money =  $this->productPrice($order->orderProducts);
        $order->pay_money =  $order->order_money;
        //分销
        if($order->pid && $order->member_id != $order->pid){
            $config = AddonHelper::getConfig();
            if(isset($config['edu_fenxiao']) && $config['edu_fenxiao'] == 1){
                //商品分销
                if(isset($config['edu_fenxiao_type']) && $config['edu_fenxiao_type'] == 1){
                   $order->fenxiao_money = $this->fxMoney($order->orderProducts);
                }
            }
        }
        
        if (!$order->save()) {
            throw new UnprocessableEntityHttpException($this->getError($order));
        }

        // 创建订单详情
        $this->createProduct($order->orderProducts, $order);
        return $order;
    }
    public function vipCreate(Order $previewForm){
        $config = AddonHelper::getConfig();
        // 生成订单
        $order = $previewForm;
        $order = $order->loadDefaultValues();
        $order->attributes = ArrayHelper::toArray($previewForm);
        $order->status = 1; //创建待支付
        $order->order_sn = date('YmdHis') . StringHelper::random(10, true);
        $order->buyer_ip = Yii::$app->request->userIP;
        //获取vip信息
        $order->orderProducts = MemberVip::find()->where(['id'=>$order->products_id,'status'=>1])->one();
        if(!$order->orderProducts || empty($order->orderProducts)){
            throw new UnprocessableEntityHttpException('vip信息不存在');
        }
        //已经是vip则不允许购买。续费的将在后续补充
        $member = !Yii::$app->user->isGuest ? Yii::$app->user->identity->member : '';
        $is_vip = Yii::$app->jhxEduService->member->isVip($member);
        if($is_vip){
            throw new UnprocessableEntityHttpException('您当前已经是vip，暂不支持续费');
        }
        $order->vip_day = $order->orderProducts->day;
        //计算价格
        $order->order_money =  $order->orderProducts->price;
        $order->pay_money =  $order->order_money;
        if (!$order->save()) {
            throw new UnprocessableEntityHttpException($this->getError($order));
        }

        // 创建订单详情
        $this->createProduct($order->orderProducts, $order);
        return $order;
    }
    /**
     * 订单商品价格
     */
    public function productPrice($orderProducts){
        $money = 0;
        $member = !Yii::$app->user->isGuest ? Yii::$app->user->identity->member : '';
        $is_vip = Yii::$app->jhxEduService->member->isVip($member);
        foreach ($orderProducts as $key => $value) {
            //订单金额计算
            if($is_vip){
                $money = bcadd($money,$value->vip_price,2);
            }else{
                $money = bcadd($money,$value->real_price,2);
            }
        }
        return $money;
    }
    /**
     * 商品分销金额
     */
    public function fxMoney($orderProducts){
        //分销金额计算
        $fenxiao_money = 0;
        foreach ($orderProducts as $key => $value) {
            if($value->fenxiao_money > 0){
                $fenxiao_money = bcadd($fenxiao_money,$value->fenxiao_money,2);
            }
        }
        return $fenxiao_money;
    }

    /**
     * 支付
     *
     * @param Order $order
     * @param int $paymentType 支付类型
     * @throws UnprocessableEntityHttpException
     * @throws \yii\web\NotFoundHttpException
     */
    public function pay(Order $order, $paymentType)
    {
        if ($order->order_status != 1) {
            throw new UnprocessableEntityHttpException('订单已经被处理，无法进行支付');
        }

        if ($order->pay_status == 1) {
            throw new UnprocessableEntityHttpException('订单已支付，请不要重复支付');
        }
        // 修改订单信息
        $order->order_status = 2;
        $order->pay_code = $paymentType;
        $order->pay_status = 1;
        $order->is_new_member = $this->findIsNewMember($order->member_id, $order->merchant_id);
        $order->pay_time = time();
        $order->save();
        //分销
        if($order->pid && $order->fenxiao_money > 0){
            $account  = Account::find()->where(['member_id'=>$order->pid])->one();
            $account->fenxiao_money = bcadd($account->fenxiao_money, $order->fenxiao_money,2);
            $account->save();
            //分销记录
            $log = new DistributeLog();
            $log->order_id = $order->id;
            $log->member_id = $order->member_id;
            $log->pid = $order->pid;
            $log->money = $order->fenxiao_money;
            $log->save();
        }
        // 加销量
        $orderProduct = $order->product;
        
        $map = ArrayHelper::map($orderProduct, 'product_id', 'num');
        $ids = array_keys($map);
        $products = Product::find()
            ->where(['in', 'id', $ids])
            ->all();
        foreach ($products as $key=>$product) {
            $num = $map[$product['id']];
            //$num = 1;
            /** @var Product $product */
            $product->virtual_sale += $num;
            $product->sale += $num;
            $product->save();
        }
    }
    /**
     * 支付
     *
     * @param Order $order
     * @param int $paymentType 支付类型
     * @throws UnprocessableEntityHttpException
     * @throws \yii\web\NotFoundHttpException
     */
    public function payVip(Order $order, $paymentType)
    {
        if ($order->order_status != 1) {
            throw new UnprocessableEntityHttpException('订单已经被处理，无法进行支付');
        }

        if ($order->pay_status == 1) {
            throw new UnprocessableEntityHttpException('订单已支付，请不要重复支付');
        }
        // 修改订单信息
        $order->order_status = 2;
        $order->pay_code = $paymentType;
        $order->pay_status = 1;
        $order->is_new_member = $this->findIsNewMember($order->member_id, $order->merchant_id);
        $order->pay_time = time();
        $order->save();
        //修改会员信息
        $member = Member::find()->where(['id'=>$order->member_id])->one();
        $member->is_vip = 1;
        $member->vip_expire = time() + ($order->vip_day * 24 * 60 *60);
        if(!$member->save()){
            throw new UnprocessableEntityHttpException($member->getErrors());
        }

        // // 加销量
        // $orderProduct = $order->product;
        // $map = ArrayHelper::map($orderProduct, 'product_id', 'num');
        // $ids = array_keys($map);
        // $products = Product::find()
        //     ->where(['in', 'id', $ids])
        //     ->all();
        // foreach ($products as $key=>$product) {
        //     $num = $orderProduct[$product['id']];
        //     /** @var Product $product */
        //     $product->virtual_sale += $num;
        //     $product->real_sale += $num;
        //     $product->save();
        // }
    }

    /**
     * 关闭订单
     *
     * @param $id
     * @param string $member_id
     * @param bool $constraint 强制关闭不校验被处理
     * @throws UnprocessableEntityHttpException
     * @throws \yii\web\NotFoundHttpException
     */
    public function close($id, $member_id = '', $constraint = false)
    {
        $order = $this->findByIdAndVerify($id, $member_id);
        // 判断订单是否已经被关闭
        if ($order->order_status == OrderStatusEnum::REPEAL) {
            throw new UnprocessableEntityHttpException('订单已经关闭');
        }
        // 判断是否是未支付的订单
        if ($constraint == false && $order->order_status != OrderStatusEnum::NOT_PAY) {
            throw new UnprocessableEntityHttpException('订单已经被处理');
        }

        // 积分返回
        if ($order->point > 0) {
            Yii::$app->services->memberCreditsLog->incrInt(new CreditsLogForm([
                'member' => $order->member,
                'num' => $order->point,
                'credit_group' => 'orderClose',
                'map_id' => $order->id,
                'remark' => '【微商城】订单关闭',
            ]));
        }

        // 取消赠送
        if ($order->give_point > 0) {
            if (
                ($order->give_point_type == 1 && $order->order_status >= OrderStatusEnum::ACCOMPLISH) ||
                ($order->give_point_type == 2 && $order->order_status >= OrderStatusEnum::SING) ||
                ($order->give_point_type == 3 && $order->order_status >= OrderStatusEnum::PAY)
            ) {
                // 取消赠送
                Yii::$app->services->memberCreditsLog->closeGiveInt(new CreditsLogForm([
                    'member' => $order->member,
                    'num' => $order->give_point,
                    'credit_group' => 'orderCloseGive',
                    'map_id' => $order->id,
                    'remark' => '【微商城】订单关闭取消赠送',
                ]));
            }
        }

        // 拼团状态修改
        $order->wholesale_id > 0 && Yii::$app->JhxEduService->marketingWholesale->cancel($order->wholesale_id);
        // 判断是否已支付的虚拟商品订单，是的话直接关闭发放的卡卷
        if ($order->order_status != OrderStatusEnum::NOT_PAY && $order->order_type == OrderTypeEnum::VIRTUAL) {
            Yii::$app->JhxEduService->orderProductVirtual->closeByOrderId($order->id);
        }

        $order->order_status = OrderStatusEnum::REPEAL;
        if (!$order->save()) {
            throw new UnprocessableEntityHttpException($this->getError($order));
        }
    }

    /**
     * 发货
     *
     * @param $id
     * @throws UnprocessableEntityHttpException
     * @throws \yii\web\NotFoundHttpException
     */
    public function consign($id)
    {
        $order = $this->findById($id);

        if ($order->order_status == OrderStatusEnum::SHIPMENTS) {
            throw new UnprocessableEntityHttpException('订单已经发货');
        }

        if ($order->order_status != OrderStatusEnum::PAY) {
            throw new UnprocessableEntityHttpException('订单已经被处理');
        }

        $order->order_status = OrderStatusEnum::SHIPMENTS;
        $order->consign_time = time();
        if (!$order->save()) {
            throw new UnprocessableEntityHttpException($this->getError($order));
        }
    }

    /**
     * 关闭订单
     *
     * @param $config
     * @param $merchant_id
     * @throws UnprocessableEntityHttpException
     * @throws \yii\web\NotFoundHttpException
     */
    public function closeAll($config, $merchant_id)
    {
        $order_buy_close_time = $config['order_buy_close_time'] ?? (new SettingForm())->order_buy_close_time;
        if ($order_buy_close_time == 0) {
            return;
        }

        $orderIds = Order::find()
            ->select('id')
            ->where(['order_status' => OrderStatusEnum::NOT_PAY])
            ->andWhere(['<=', 'created_at', time() - $order_buy_close_time * 60])
            ->andFilterWhere(['merchant_id' => $merchant_id])
            ->column();

        try {
            foreach ($orderIds as $id) {
                $this->close($id);
                // 记录操作
                Yii::$app->JhxEduService->orderAction->create('自动关闭', $id, OrderStatusEnum::NOT_PAY, 0, '系统');
            }
        } catch (\Exception $e) {
            p($e->getMessage());die();
        }
    }
    //用户是否已购买该课程
    public function buyed($product_id,$member_id){
        $rs = OrderProduct::find()
            ->where(['product_id' => $product_id, 'member_id' => $member_id])
            ->one();
        if($rs->order_id){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 查询订单
     */
    public function query(OrderQueryForm $queryForm)
    {
        /** @var ActiveQuery $data */
        $data = Order::find()
            ->alias('o')
            ->where(['>=', 'o.status', StatusEnum::DISABLED])
            ->andFilterWhere(['o.member_id' => $queryForm->member_id])
            ->andFilterWhere(['o.pay_status' => $queryForm->pay_status])
            ->andFilterWhere(['like', 'o.order_sn', $queryForm->order_sn])
            ->andFilterWhere(['between', 'o.created_at', $queryForm->start_time, $queryForm->end_time])
            ->andFilterWhere(['o.merchant_id' => $this->getMerchantId()])
            ->with('product')
            ->select([
                'o.id',
                'o.merchant_id',
                'order_sn',
                'o.order_status',
                'pay_code',
                'o.member_id',
                'o.order_money',
                'o.pay_status',
                'pay_time',
                'pay_money',
                'o.created_at',
            ]);
        $pages = new Pagination([
            'totalCount' => $data->count(),
            'pageSize' => $this->pageSize,
            'validatePage' => false,
        ]);
        $models = $data->offset($pages->offset)
            ->orderBy('id desc')
            ->asArray()
            ->limit($pages->limit)
            ->all();

        return $models;
    }

    /**
     * @param $order_id
     * @return array|null|\yii\db\ActiveRecord|Order
     */
    public function findById($order_id)
    {
        return Order::find()
            ->where(['id' => $order_id, 'status' => 1])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->one();
    }

    /**
     * 查询并校验订单
     *
     * @param $id
     * @param string $member_id
     * @return array|\yii\db\ActiveRecord|null|Order
     * @throws UnprocessableEntityHttpException
     */
    public function findByIdAndVerify($id, $member_id = '')
    {
        $model = Order::find()
            ->where(['id' => $id, 'status' => StatusEnum::ENABLED])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->one();

        if (!$model) {
            throw new UnprocessableEntityHttpException('订单不存在');
        }

        if ($member_id && $member_id != $model['buyer_id']) {
            throw new UnprocessableEntityHttpException('权限不足');
        }

        return $model;
    }

    /**
     * @param $order_id
     * @return array|null|\yii\db\ActiveRecord|Order
     */
    public function findByOrderSn($order_sn)
    {
        return Order::find()
            ->where(['order_sn' => $order_sn, 'status' => 1])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->one();

    }
    /**
     * 获取订单数量
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getOrderCountGroupByStatus()
    {
        $order = Order::find()
            ->select(['order_status', 'count(id) as count'])
            ->where(['status' => StatusEnum::ENABLED])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->groupBy('order_status')
            ->asArray()
            ->all();

        return ArrayHelper::arrayKey($order, 'order_status');
    }
    /**
     * 获取已购课程数量
     *
     * @param string $member_id
     * @return false|string|null
     */
    public function getPayCount($member_id = '')
    {
        return OrderProduct::find()
            ->select(['count(distinct product_id) as count'])
            ->andFilterWhere(['member_id' => $member_id])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->scalar();
    }
    /**
     * 获取我的订单数量
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getOrderCountGroupByMemberId($member_id)
    {
        $order_status = [
            OrderStatusEnum::NOT_PAY, // 待付款
            OrderStatusEnum::PAY, // 待发货
            OrderStatusEnum::SHIPMENTS, // 待收货
        ];

        $order = Order::find()
            ->select(['order_status', 'count(id) as count'])
            ->where(['status' => StatusEnum::ENABLED])
            ->andWhere(['buyer_id' => $member_id])
            ->andWhere(['in', 'order_status', $order_status])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->groupBy('order_status')
            ->asArray()
            ->all();

        $memberStatus = [];
        // 待评价
        $memberStatus[3] = Order::find()
            ->select(['count(id) as count'])
            ->where(['status' => StatusEnum::ENABLED])
            ->andWhere(['buyer_id' => $member_id])
            ->andWhere(['review_status' => StatusEnum::DISABLED])
            ->andWhere(['in', 'order_status', [OrderStatusEnum::SING, OrderStatusEnum::ACCOMPLISH]])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->scalar();
        // 售后
        $memberStatus[-1] = Yii::$app->JhxEduService->orderProduct->getAfterSaleCount($member_id);
        $order = ArrayHelper::arrayKey($order, 'order_status');
        foreach ($order_status as $status) {
            // 正常统计订单数量
            if (isset($order[$status])) {
                $memberStatus[$status] = $order[$status]['count'];
            } elseif ($status >= 0) {
                $memberStatus[$status] = 0;
            }
        }



        return $memberStatus;
    }

    /**
     * @return int|string
     */
    public function getCount($order_type = '')
    {
        return Order::find()
            ->select('id')
            ->where(['status' => StatusEnum::ENABLED])
            ->andFilterWhere(['order_type' => $order_type])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->count();
    }

    /**
     * 获取最新的订单
     *
     * @return array|\yii\db\ActiveRecord|null
     */
    public function findLastPay()
    {
        return Order::find()
            ->select(['created_at', 'order_type', 'pay_money', 'buyer_id', 'user_name'])
            ->where(['pay_status' => StatusEnum::ENABLED])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->asArray()
            ->one();
    }

    /**
     * 获取指定时间内下单用户数量
     *
     * @param $start_time
     * @param $end_time
     * @return false|string|null
     */
    public function findMemberCountByTime($start_time = '', $end_time = '', $is_new_member = '')
    {
        return Order::find()
            ->select(['buyer_id'])
            ->where(['pay_status' => StatusEnum::ENABLED])
            ->andFilterWhere(['between', 'created_at', $start_time, $end_time])
            ->andFilterWhere(['is_new_member' => $is_new_member])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->groupBy('buyer_id')
            ->count();
    }

    /**
     * 查询是否是新顾客
     *
     * @param $member_id
     * @param $merchant_id
     * @return int
     */
    public function findIsNewMember($member_id, $merchant_id)
    {
        $order = Order::find()
            ->select('id')
            ->where([
                'member_id' => $member_id,
                'merchant_id' => $merchant_id,
                'pay_status' => StatusEnum::ENABLED,
            ])
            ->one();

        return !empty($order) ? StatusEnum::DISABLED : StatusEnum::ENABLED;
    }

    /**
     * 获取订单数量、总金额、产品数量
     *
     * @return array|\yii\db\ActiveRecord|null
     */
    public function getStatByTime($time, $select = [])
    {
        $select = ArrayHelper::merge([
            'sum(product_count) as product_count',
            'count(id) as count',
            'sum(pay_money) as pay_money'
        ], $select);
        return Order::find()
            ->select($select)
            ->where(['pay_status' => StatusEnum::ENABLED])
            ->andWhere(['>', 'pay_time', $time])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->asArray()
            ->one();
    }

    /**
     * 获取每天订单数量、总金额、产品数量
     *
     * @return array|\yii\db\ActiveRecord|null
     */
    public function getDayStatByTime($time)
    {
        return Order::find()
            ->select([
                'sum(product_count) as product_count',
                'count(id) as count',
                'sum(pay_money) as pay_money',
                "from_unixtime(created_at, '%Y-%c-%d') as day"
            ])
            ->where(['pay_status' => StatusEnum::ENABLED])
            ->andWhere(['>', 'pay_time', $time])
            ->groupBy(['day'])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->asArray()
            ->all();
    }

    /**
     * @param string $type
     * @param string $count_sql
     * @return array
     */
    public function getBetweenCountStatToEchant($type)
    {
        $fields = [
            'count' => '订单笔数',
            'product_count' => '订单量',
        ];

        // 获取时间和格式化
        list($time, $format) = EchantsHelper::getFormatTime($type);
        // 获取数据
        return EchantsHelper::lineOrBarInTime(function ($start_time, $end_time, $formatting) {
            return Order::find()
                ->select([
                    'count(id) as count',
                    'sum(product_count) as product_count',
                    "from_unixtime(created_at, '$formatting') as time"
                ])
                ->where(['pay_status' => StatusEnum::ENABLED])
                ->andWhere(['between', 'pay_time', $start_time, $end_time])
                ->groupBy(['time'])
                ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
                ->asArray()
                ->all();
        }, $fields, $time, $format);
    }

    /**
     * @param string $type
     * @param string $count_sql
     * @return array
     */
    public function getBetweenProductMoneyAndCountStatToEchant($type)
    {
        $fields = [
            'pay_money' => '下单金额',
            // 'product_count' => '下单量',
        ];

        // 获取时间和格式化
        list($time, $format) = EchantsHelper::getFormatTime($type);
        // 获取数据
        return EchantsHelper::lineOrBarInTime(function ($start_time, $end_time, $formatting) {
            return Order::find()
                ->select([
                    'sum(pay_money) as pay_money',
                   // 'sum(product_count) as product_count',
                    "from_unixtime(created_at, '$formatting') as time"
                ])
                ->where(['pay_status' => StatusEnum::ENABLED])
                ->andWhere(['between', 'pay_time', $start_time, $end_time])
                ->groupBy(['time'])
                ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
                ->asArray()
                ->all();
        }, $fields, $time, $format);
    }

    /**
     * @param string $type
     * @param string $count_sql
     * @return array
     */
    public function getOrderCreateCountStat($type)
    {
        $fields = [
            [
                'name' => '下单数量',
                'type' => 'bar',
                'field' => 'count',
            ],
            [
                'name' => '支付数量',
                'type' => 'bar',
                'field' => 'pay_count',
            ],
            [
                'name' => '下单支付转化率',
                'type' => 'line',
                'field' => 'pay_rate',
            ],
        ];

        // 获取时间和格式化
        list($time, $format) = EchantsHelper::getFormatTime($type);
        // 获取数据
        return EchantsHelper::lineOrBarInTime(function ($start_time, $end_time, $formatting) {
            $data = Order::find()
                ->select([
                    'count(id) as count',
                    'sum(pay_status) as pay_count',
                    "from_unixtime(created_at, '$formatting') as time"
                ])
                ->andWhere(['between', 'created_at', $start_time, $end_time])
                ->groupBy(['time'])
                ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
                ->asArray()
                ->all();

            foreach ($data as &$datum) {
                $datum['pay_rate'] = BcHelper::mul(BcHelper::div($datum['pay_count'], $datum['count']), 100);
            }

            return $data;
        }, $fields, $time, $format);
    }

    /**
     * @param string $type
     * @param string $count_sql
     * @return array
     */
    public function getBetweenProductCountAndCountStatToEchant($type)
    {
        $fields = [
             'product_count' => '商品售出数',
        ];

        // 获取时间和格式化
        list($time, $format) = EchantsHelper::getFormatTime($type);
        // 获取数据
        return EchantsHelper::lineOrBarInTime(function ($start_time, $end_time, $formatting) {
            return Order::find()
                ->select([
                    'sum(product_count) as product_count',
                    "from_unixtime(created_at, '$formatting') as time"
                ])
                ->where(['pay_status' => StatusEnum::ENABLED])
                ->andWhere(['between', 'pay_time', $start_time, $end_time])
                ->groupBy(['time'])
                ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
                ->asArray()
                ->all();
        }, $fields, $time, $format);
    }

    /**
     * 订单来源统计
     *
     * @return array
     */
    public function getFormStat($type)
    {
        $fields = array_values(AccessTokenGroupEnum::getMap());

        // 获取时间和格式化
        list($time, $format) = EchantsHelper::getFormatTime($type);
        // 获取数据
        return EchantsHelper::pie(function ($start_time, $end_time) use ($fields) {
            $data = Order::find()
                ->select(['count(id) as value', 'order_from'])
                ->where(['status' => StatusEnum::ENABLED])
                ->andFilterWhere(['between', 'created_at', $start_time, $end_time])
                ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
                ->groupBy(['order_from'])
                ->asArray()
                ->all();

            foreach ($data as &$datum) {
                $datum['name'] = AccessTokenGroupEnum::getValue($datum['order_from']);
            }

            return [$data, $fields];
        }, $time);
    }

    /**
     * 订单类型统计
     *
     * @return array
     */
    public function getOrderTypeStat($type)
    {
        $fields = array_values(OrderTypeEnum::getMap());

        // 获取时间和格式化
        list($time, $format) = EchantsHelper::getFormatTime($type);
        // 获取数据
        return EchantsHelper::pie(function ($start_time, $end_time) use ($fields) {
            $data = Order::find()
                ->select(['count(id) as value', 'order_type'])
                ->where(['status' => StatusEnum::ENABLED])
                ->andFilterWhere(['between', 'created_at', $start_time, $end_time])
                ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
                ->groupBy(['order_type'])
                ->asArray()
                ->all();

            foreach ($data as &$datum) {
                $datum['name'] = OrderTypeEnum::getValue($datum['order_type']);
            }

            return [$data, $fields];
        }, $time);
    }

    /**
     * 获取区间订单数据
     *
     * @param $start_time
     * @param $end_time
     * @param $formatting
     * @param $count_sql
     * @return array|\yii\db\ActiveRecord[]
     */
    protected function getBetweenCountStat($start_time, $end_time, $formatting, $count_sql)
    {
        return Order::find()
            ->select([$count_sql, "from_unixtime(created_at, '$formatting') as time"])
            ->where(['pay_status' => StatusEnum::ENABLED])
            ->andWhere(['between', 'pay_time', $start_time, $end_time])
            ->groupBy(['time'])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->asArray()
            ->all();
    }

    /**
     * 创建产品
     *
     * @param $orderProducts
     * @param $sku
     * @param Order $order
     * @throws UnprocessableEntityHttpException
     */
    protected function createProduct($orderProducts, Order $order)
    {
        if(is_array($orderProducts) && $order->order_type == 1){
            /** @var OrderProduct $model */
            foreach ($orderProducts as $p) {
                $model = new OrderProduct();
                //订单商品表
                $model->member_id = $order->member_id;
                $model->order_id = $order->id;
                $model->name = $p->name;
                $model->price = $p->real_price;
                $model->picture = $p->picture;
                $model->product_id = $p->id;
                if (!$model->save()) {
                    throw new UnprocessableEntityHttpException($this->getError($model));
                }
            }
        }else if($order->order_type == 2){
            //vip购买
            $model = new OrderProduct();
            $model->member_id = $order->member_id;
            $model->order_id = $order->id;
            $model->name = $orderProducts->name;
            $model->price = $orderProducts->price;
            $model->product_id = $orderProducts->id;
            if (!$model->save()) {
                throw new UnprocessableEntityHttpException($this->getError($model));
            }
        }
            
    }

    /**
     * @return SettingForm|mixed
     */
    protected function getSetting()
    {
        if (!$this->_setting) {
            $setting = new SettingForm();
            $setting->attributes = AddonHelper::getConfig();
            $this->_setting = $setting;
        }

        return $this->_setting;
    }
}